<template>

  <popup :title="title" @confirm="handleSubmit" ref="popupRef">

    <el-tag v-for="item in listUserRoleData"
            size="large"
            closable
            disable-transitions="true"
            @close="handleClose(item.role_id)"
            style="margin-right: 15px"
    >
      {{ item.role_id_name }}
    </el-tag>

    <el-select v-if="selectVisible" placeholder="请选择角色">
      <el-option
          v-for="item in listRoleData"
          :key="item.id"
          :label="item.name"
          :value="item.id"
          @click="clickSelect(item)"
      />
    </el-select>
    <el-button v-else type="success" plain @click="showSelect">
      + 角色
    </el-button>
  </popup>

</template>

<script setup>
import popup from '@/components/popup/index.vue'
import {onMounted, reactive, ref, shallowRef} from "vue";
import {listRole, addRole} from '@/api/user'
import {list} from '@/api/role'

const popupRef = shallowRef(popup)
const emit = defineEmits(['success'])

const title = ref('角色列表')
const listUserRoleData = ref({})
const listRoleData = ref([])
const formData = reactive({
  user_id: 0,
  role_ids: {},
})

const selectVisible = ref(false)
const showSelect = () => {
  selectVisible.value = true
}
const clickSelect = (item) => {
  listUserRoleData.value[item.id] = {role_id: item.id, role_id_name: item.name}
  formData.role_ids[item.id] = item.id
  selectVisible.value = false
}

const handleSubmit = async () => {
  await addRole(formData)
  emit('success')
}

const handleClose = (id) => {
  delete listUserRoleData.value[id]
  delete formData.role_ids[id]
}

const setFormData = async (row) => {
  formData["user_id"] = row.id
  listRole(formData).then((data) => {
    data.forEach((item) => {
      listUserRoleData.value[item.role_id] = item
      formData.role_ids[item.role_id] = item.role_id
    })
  })
}

onMounted(() => {
  list({page_size: 1000}).then((data) => {
    data.list.forEach((item) => {
      listRoleData.value.push(item)
    })
  })
})

defineExpose({
  setFormData
})
</script>

<style scoped>

</style>